package com.example.nongye.ui.activity;

import android.os.Bundle;
import android.text.InputFilter;
import android.text.TextUtils;

import androidx.appcompat.app.AppCompatActivity;

import com.example.nongye.R;
import com.example.nongye.databinding.ActivityConfBinding;
import com.example.nongye.utils.StringUtils;
import com.example.nongye.utils.ToastUtils;
import com.jaeger.library.StatusBarUtil;
import com.tencent.mmkv.MMKV;

public class ConfActivity extends AppCompatActivity {

    private ActivityConfBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityConfBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        StatusBarUtil.setColor(this, getResources().getColor(R.color.white), 0);
        StatusBarUtil.setLightMode(this);
        binding.btnBack.setOnClickListener(view -> finish());
        binding.btnSave.setOnClickListener(view -> {
            String phone = binding.etPhone.getText().toString();
            String name = binding.etName.getText().toString();
            String password = binding.etPwd.getText().toString();
            String card = binding.etCard.getText().toString();
            String yue = binding.etYue.getText().toString();
            if (!TextUtils.isEmpty(phone) && !StringUtils.isMobile(phone)) {
                ToastUtils.showShort("请输入正确的手机号");
                return;
            }
            if (!TextUtils.isEmpty(card) && !StringUtils.isNumber(card)) {
                ToastUtils.showShort("卡号不是纯数字");
            }
            binding.etYue.setFilters(new InputFilter[]{lengthFilter});
            MMKV.defaultMMKV().putString("phone", phone);
            MMKV.defaultMMKV().putString("name", name);
            MMKV.defaultMMKV().putString("password", password);
            MMKV.defaultMMKV().putString("card", card);
            MMKV.defaultMMKV().putString("yue", yue);
            ToastUtils.showShort("保存成功");
        });
        initView();
    }

    private void initView() {
        binding.etPhone.setText(MMKV.defaultMMKV().getString("phone", ""));
        binding.etName.setText(MMKV.defaultMMKV().getString("name", ""));
        binding.etPwd.setText(MMKV.defaultMMKV().getString("password", ""));
        binding.etCard.setText(MMKV.defaultMMKV().getString("card", ""));
        binding.etYue.setText(MMKV.defaultMMKV().getString("yue", ""));
        binding.btnBack.setOnClickListener(view -> finish());
    }

    private InputFilter lengthFilter = (source, start, end, dest, dstart, dend) -> {
        if (dest.length() == 0 && source.equals(".")) {
            return "0.";
        }
        String dValue = dest.toString();
        String[] splitArray = dValue.split("\\.");
        if (splitArray.length > 1) {
            String dotValue = splitArray[1];
            if (dotValue.length() == 2) {
                return "";
            }
        }
        return null;
    };
}